package com.yijietong.yiliao.doctor.network.retrofit;


import java.io.IOException;
import java.net.URLEncoder;


import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by WuXiaolong on 2016/3/24.
 */
public class RetrofitClient {
    public static Retrofit mRetrofit;
    private static OkHttpClient.Builder builder;

    public static Retrofit retrofit(String baseUrl,OkHttpClient okHttpClient) {
        if (mRetrofit == null) {
            // 首次创建对象的时候
            mRetrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .client(okHttpClient)
                    .build();
        } else if(baseUrl!=null && !baseUrl.equals(mRetrofit.baseUrl().toString())) {
            // 非首次，并且baseUrl不同。
            mRetrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .client(okHttpClient)
                    .build();
        }
        return mRetrofit;
    }

    public static OkHttpClient getOkHttpClientDefault(){
        if(builder==null) {
            builder = new OkHttpClient.Builder();
            // Log信息拦截器
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            //设置 Debug Log 模式
            builder.addInterceptor(loggingInterceptor);

            Interceptor interceptor = new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    return chain.proceed(chain.request());
                }
            };
            builder.addInterceptor(interceptor);
        }
        return builder.build();
    }

}
